﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsBidCategoryTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// Bid Category Business Object
    /// </summary>

    public class BidCategory : BOBase
    {


        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected BidCategory() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the BidCategory.
        /// </summary>
        public int BidCategoryID
        {
            get { return _BidcategoryID; }
            set
            {
                if (_BidcategoryID != value)
                {
                    if (OnPropertyChanging("BidCategoryID", _BidcategoryID, value))
                    {
                        int oldValue = _BidcategoryID;
                        _BidcategoryID = value;

                        OnPropertyChanged("BidCategoryID", oldValue, value);
                    }
                }
            }
        }  private int _BidcategoryID = -1;

        /// <summary>
        /// Bid Category Value.
        /// </summary>
        public string BidCategoryName
        {
            get { return _Bidcategoryname; }
            set
            {
                if (_Bidcategoryname != value)
                {
                    if (OnPropertyChanging("BidCategoryName", _Bidcategoryname, value))
                    {
                        string oldValue = _Bidcategoryname;
                        _Bidcategoryname = value;
                        OnPropertyChanged("BidCategoryName", oldValue, value);
                    }
                }
            }
        }  private string _Bidcategoryname = null;


        /// <summary>
        /// Bid Category Description.
        /// </summary>
        public string BidCategoryDescription
        {
            get { return _Bidcategorydescription; }
            set
            {
                if (_Bidcategorydescription != value)
                {
                    if (OnPropertyChanging("BidCategoryDescription", _Bidcategorydescription, value))
                    {
                        string oldValue = _Bidcategorydescription;
                        _Bidcategorydescription = value;
                        OnPropertyChanged("BidCategoryDescription", oldValue, value);
                    }
                }
            }
        }  private string _Bidcategorydescription = null;


        /// <summary>
        /// Date/time at which the BidCategory was created.
        /// </summary>
        public DateTime? AddedDate
        {
            get { return _addedDate; }
            set
            {
                if (_addedDate != value)
                {
                    if (OnPropertyChanging("AddedDate", _addedDate, value))
                    {
                        DateTime? oldValue = _addedDate;
                        _addedDate = value;
                        OnPropertyChanged("AddedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _addedDate = null;

        /// <summary>
        /// Date/time at which the BidCategory was updated.
        /// </summary>
        public DateTime? UpdatedDate
        {
            get { return _updatedDate; }
            set
            {
                if (_updatedDate != value)
                {
                    if (OnPropertyChanging("UpdatedDate", _updatedDate, value))
                    {
                        DateTime? oldValue = _updatedDate;
                        _updatedDate = value;
                        OnPropertyChanged("UpdatedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _updatedDate = null;


        /// <summary>
        /// True iff the Admin has made this BidCategory Active (i.e. to be used in the application).
        /// </summary>
        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                if (_isActive != value)
                {
                    if (OnPropertyChanging("IsActive", _isActive, value))
                    {
                        bool oldValue = _isActive;
                        _isActive = value;
                        OnPropertyChanged("IsActive", oldValue, value);
                    }
                }
            }
        }  private bool _isActive = false;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty BidCategory object.
        /// </summary>
        public static BidCategory CreateNew()
        {
            BidCategory obj = new BidCategory();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.AddedDate = DateTime.Now;
            obj.UpdatedDate = DateTime.Now;
            obj.IsActive = true;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static BidCategory CreateNew(BidCategoryCollection collection)
        {
            BidCategory obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (BidCategory Bidcategory in collection)
            {
                if (Bidcategory.BidCategoryID < minVal)
                    minVal = Bidcategory.BidCategoryID;
            }
            obj.BidCategoryID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllBidCategories

        /// <summary>
        /// Returns a collection of all BidCategory.
        /// </summary>
        public static BidCategoryCollection GetAllBidCategories()
        {
            BidCategoryTableAdapter adapter = new BidCategoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsBidCategory.BidCategoryDataTable tbl = adapter.GetData(null);

            BidCategoryCollection list = new BidCategoryCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsBidCategory.BidCategoryRow row in tbl.Rows)
                {
                    BidCategory Bidcategory = new BidCategory();
                    RelationalToObject(Bidcategory, row);
                    list.Add(Bidcategory);
                }
            }

            return (list);
        }

        #endregion

        #region GetBidCategoryByID

        /// <summary>
        /// Returns an BidCategory object for the specified 'BidCategoryID' or null if no BidCategory with the specified parameter(s) exists.
        /// </summary>
        public static BidCategory GetBidCategoryByID(int Bidcategoryid)
        {
            BidCategoryTableAdapter adapter = new BidCategoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsBidCategory.BidCategoryDataTable tbl = adapter.GetData(Bidcategoryid);

            if (tbl.Rows.Count == 1)
            {
                BidCategory dc = new BidCategory();
                RelationalToObject(dc, tbl.Rows[0]);
                return (dc);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'Bid' returned more than one record.");

            return (null);
        }

        #endregion

        #region GetBidCategoryByBidCategoryName

        /// <summary>
        /// Returns an BidCategory object for the specified 'BidCategoryName' or null if no BidCategory with the specified parameter(s) exists.
        /// </summary>
        //public static BidCategory GetBidCategoryByBidCategoryName(string bidcategoryname)
        //{
        //    BidCategoryTableAdapter adapter = new BidCategoryTableAdapter();
        //    adapter.Connection = AppSettings.GetDbConn();
        //    dsBidCategory.BidCategoryDataTable tbl = adapter.GetDataByBidCategoryName(bidcategoryname);

        //    if (tbl.Rows.Count == 1)
        //    {
        //        BidCategory bidcategory = new BidCategory();
        //        RelationalToObject(bidcategory, tbl.Rows[0]);
        //        return (bidcategory);
        //    }
        //    else if (tbl.Rows.Count > 1)
        //        throw new ApplicationException("Database integrity error: Specified 'bidcategory' returned more than one bidcategory.");

        //    return (null);
        //}

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified BidCategory.
        /// </summary>
        public static void Update(BidCategory obj)
        {
            bool updateBidCategory = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateBidCategory = (obj.ObjState != ObjectState.Unchanged);

                if (!updateBidCategory)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsBidCategory.BidCategoryDataTable tbl = null;
            if (updateBidCategory)
            {
                BidCategoryTableAdapter adapter = new BidCategoryTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();


                tbl = new dsBidCategory.BidCategoryDataTable();
                dsBidCategory.BidCategoryRow row = tbl.NewBidCategoryRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (BidCategoryID <= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("BidCategoryID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // UserName is required.
                if ((BidCategoryName == null) || (BidCategoryName.Trim().Length == 0))
                {
                    Errors.Add(new ValidationError("BidCategoryName", "BidCategory is required.", ValidationError.Severity.Error));
                }
                else if (ObjState == ObjectState.Added)
                {

                }

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("BidCategory: DCID={0}, BidCategoryName={1}, {2}", BidCategoryID, BidCategoryName, BidCategoryDescription));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more Bid objects.
    /// </summary>

    public class BidCategoryCollection : List<BidCategory>
    {
        #region Types

        public class UserComparer : IComparer<BidCategory>
        {
            public int Compare(BidCategory bc1, BidCategory bc2)
            {
                return (String.Compare(bc1.BidCategoryName, bc2.BidCategoryName));
            }
        }

        #endregion

        #region Public Methods

        #region FindByBidCategoryID

        public BidCategory FindByBidCategoryID(int BidcategoryID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].BidCategoryID == BidcategoryID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindByBidCategory

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public BidCategory FindByBidCategory(string Bidcategoryname)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].BidCategoryName == Bidcategoryname)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion

    }
}
